package com.valuegroup.smarttodo.ui.todo.task.detail;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.transition.TransitionInflater;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Task;
import com.valuegroup.smarttodo.data.vo.KeyValueVo;
import com.valuegroup.smarttodo.plugins.ClickableTextView;
import com.valuegroup.smarttodo.plugins.CustomTextView;
import com.valuegroup.smarttodo.plugins.ElasticDragDismissFrameLayout;
import com.valuegroup.smarttodo.plugins.MultilineEditText;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.ui.programme.curriculum.CurriculumOrderActivity;
import com.valuegroup.smarttodo.ui.programme.goals.detail.GoalsDetailActivity;
import com.valuegroup.smarttodo.util.AlertUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 任务详情页
 */
public class TaskDetailActivity extends BaseActivity {


    @BindView(R.id.task_content_frame)
    ElasticDragDismissFrameLayout draggableFrame;
    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.task_trunk_check)
    AppCompatCheckBox taskTrunCheck;
    @BindView(R.id.task_trunk_text)
    ClickableTextView taskTrunkText;
    @BindView(R.id.task_trunk_edit)
    MultilineEditText taskTrunkEdit;
    @BindView(R.id.header_shadow)
    View headerShadow;
    @BindView(R.id.taskDetailEditDateTv)
    TextView taskDetailEditDateTv;
    @BindView(R.id.taskDetailDeleteImg)
    ImageView taskDetailDeleteImg;
    @BindView(R.id.taskDetailStartImg)
    AppCompatCheckBox taskDetailStartImg;
    @BindView(R.id.task_content_branch_list)
    RecyclerView recyclerView;
    @BindView(R.id.labSource)
    TextView labSource;
    @BindView(R.id.layoutLabSource)
    LinearLayout layoutLabSource;

    private Long DATA_ID;
    private Integer DATA_POSITION;
    private Task DATA;
    private TaskDetailAdapter taskItemAdapter;
    private KeyValueVo DATA_SOURCE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taskdetail);
        ButterKnife.bind(this);

        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getTaskService().load(DATA_ID);
        if (DATA == null) {
            AlertUtils.showToast(this, R.string.not_found_record);
            finish();
            return;
        }

        initView();
        initData();
    }


    private void initData() {

        taskTrunkText.setText(DATA.getTitle());
        taskTrunCheck.setChecked(DATA.getIsFinish());
        taskDetailStartImg.setChecked(DATA.getIsStar());
        taskDetailEditDateTv.setText(String.format(getResources().getString(DATA.getIsFinish() ? R.string.finish_time : R.string.update_time), DateUtils.date2str(DATA.getIsFinish() ? DATA.getFinishDt() : DATA.getUpdatedDt(), DateUtils.F33)));

        taskItemAdapter = new TaskDetailAdapter(this, getWindow().getDecorView(), DATA_ID);
        recyclerView.setAdapter(taskItemAdapter);

        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(new TaskDetailTouchHelper(taskItemAdapter, this));
        mItemTouchHelper.attachToRecyclerView(recyclerView);

        // 事件源
        layoutLabSource.setVisibility(View.GONE);
        if (DATA.getTaskType() == AppStatus.TaskType.GOAL || DATA.getTaskType() == AppStatus.TaskType.STUDY) {
            DATA_SOURCE = ServiceFactory.getInstance().getTaskService().getTaskSource(DATA.getId());
            if (DATA_SOURCE != null) {
                labSource.setText("来源:" + DATA_SOURCE.getKey());
                layoutLabSource.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initView() {

        // 顶部返回按钮 > 设置按钮颜色（放置在图片上，可使用Glide框架在加载图片时判断图片颜色，对按钮进行动态设置）
        btnBack.setColorFilter(ContextCompat.getColor(this, R.color.textHint));

        // 弹性阻力消除框架布局
        draggableFrame.addListener(new ElasticDragDismissFrameLayout.SystemChromeFader(this) {
            @Override
            public void onDragDismissed() {
                // if we drag dismiss downward then the default reversal of the enter
                // transition would slide content upward which looks weird. So reverse it.
                if (draggableFrame.getTranslationY() > 0) {
                    getWindow().setReturnTransition(
                            TransitionInflater.from(TaskDetailActivity.this)
                                    .inflateTransition(R.transition.about_return_downward));
                }
                setCloseParams();
                finishAfterTransition();
            }
        });

        taskTrunkEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 光标移动到末尾
                    taskTrunkEdit.setSelection(taskTrunkEdit.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) taskTrunkEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(taskTrunkEdit, 0);
                } else {
                    taskTrunkEdit.setVisibility(View.GONE);
                    taskTrunkText.setText(taskTrunkEdit.getText());
                    taskTrunkText.setVisibility(View.VISIBLE);

                    // 保存标题
                    if (!TextUtils.isEmpty(taskTrunkEdit.getText())) {
                        ServiceFactory.getInstance().getTaskService().saveTaskTitle(DATA.getId(), taskTrunkEdit.getText().toString());
                    }
                }
            }
        });

        taskTrunkEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    taskTrunkText.setText(v.getText());
                    taskTrunkText.setVisibility(View.VISIBLE);
                    taskTrunkEdit.setVisibility(View.GONE);
                }
                return true;
            }
        });

        // 任务主干选中状态控制
        taskTrunCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                // 保存完成状态
                ServiceFactory.getInstance().getTaskService().doFinish(DATA.getId(), b);
                if (b) {
                    taskTrunkText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textHint));
                    taskTrunkText.getPaint().setStrikeThruText(true);// setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                } else {
                    taskTrunkText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.textDefault));
                    taskTrunkText.getPaint().setStrikeThruText(false);// setFlags(0);
                }
            }
        });

        // 星标选中状态控制
        taskDetailStartImg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                ServiceFactory.getInstance().getTaskService().doStar(DATA.getId(), b);
            }
        });

        assert recyclerView != null;
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                // 滚动时回调

                /*
                canScrollVertically (int direction)
                这个方法是判断View在竖直方向是否还能向上，向下滑动。
                其中，direction为 -1 表示手指向下滑动（屏幕向上滑动）， 1 表示手指向上滑动（屏幕向下滑动）。
                canScrollHorizontally (int direction)
                例如：
                RecyclerView.canScrollVertically(1)的值表示是否能向下滚动，false表示已经滚动到底部
                RecyclerView.canScrollVertically(-1)的值表示是否能向上滚动，false表示已经滚动到顶部
                */

                if (recyclerView.canScrollVertically(-1)) {
                    headerShadow.setVisibility(View.VISIBLE);
                } else {
                    headerShadow.setVisibility(View.GONE);
                }

                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                // 滚动状态变化时回调
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // btnBack button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @OnClick({R.id.btnBack, R.id.task_trunk_text, R.id.taskDetailDeleteImg, R.id.labSource})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                // 头部返回按钮返回事件
                setCloseParams();
                finishAfterTransition();
                break;

            case R.id.task_trunk_text:
                // 头部任务主干点击事件
                if (DATA.getTaskType() == AppStatus.TaskType.GOAL || DATA.getTaskType() == AppStatus.TaskType.STUDY) {
                    AlertUtils.showToast(this, getResources().getString(R.string.dont_change_task_title));
                    return;
                }

                taskTrunkEdit.setText(taskTrunkText.getText());
                taskTrunkEdit.setVisibility(View.VISIBLE);
                taskTrunkText.setVisibility(View.GONE);

                // 获得焦点
                taskTrunkEdit.setFocusable(true);
                taskTrunkEdit.setFocusableInTouchMode(true);
                taskTrunkEdit.requestFocus();

                break;
            case R.id.taskDetailDeleteImg:
                if (DATA.getTaskType() == AppStatus.TaskType.GOAL || DATA.getTaskType() == AppStatus.TaskType.STUDY) {
                    AlertUtils.showToast(this, getResources().getString(R.string.dont_del_task));
                    return;
                }

                AlertUtils.delDialog(this, R.string.task, (dialog, which) -> {
                    ServiceFactory.getInstance().getTaskService().delTask(DATA.getId());
                    finish();
                });
                break;
            case R.id.labSource:
                if (DATA_SOURCE != null) {
                    if (DATA.getTaskType() == AppStatus.TaskType.GOAL) {
                        Intent intent = new Intent(view.getContext(), GoalsDetailActivity.class);
                        intent.putExtra(GoalsDetailActivity.PARAMS_KEY, DATA_SOURCE.getId());
                        startActivityForResult(intent, 1005);
                    } else if (DATA.getTaskType() == AppStatus.TaskType.STUDY) {
                        Intent intent = new Intent(view.getContext(), CurriculumOrderActivity.class);
                        intent.putExtra(CurriculumOrderActivity.PARAMS_KEY, DATA_SOURCE.getId());
                        startActivityForResult(intent, 1005);
                    }
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, DATA_ID);
        setResult(RESULT_OK, intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        // 重新加载数据（数据在外被删除时会产生异常）
        DATA = ServiceFactory.getInstance().getTaskService().load(DATA_ID);
        if (DATA == null) {
            finish();
            return;
        }

        initData();
    }


}
